/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cc.altius.service.impl;

import cc.altius.dao.SmsDao;
import cc.altius.model.SmsDetails;
import cc.altius.model.SmsSendData;
import cc.altius.model.SmsSituation;
import cc.altius.model.SmsTemplate;
import cc.altius.model.SmsType;
import cc.altius.service.SmsService;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 *
 * @author sagar
 */
@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    private SmsDao smsDao;

    @Override
    public List<SmsDetails> getFailedSmsList() {
        return this.smsDao.getFailedSmsList();
    }

    @Override
    public List<SmsType> getSmsTypeList() {
        return this.smsDao.getSmsTypeList();
    }

    @Override
    public List<SmsSituation> getSmsSituationList() {
        return this.smsDao.getSmsSituationList();
    }
    
//    @Override
//    public int UpdateSms(SmsDetails sms) {
//        return this.smsDao.UpdateSms(sms);
//    }

//    @Override
//    public SmsType SmsTypeName(int smsTypeId) {
//        return this.smsDao.SmsTypeName(smsTypeId);
//    }

    @Override
    public SmsTemplate SmsTemplateName(int smsTemplateId) {
        return this.smsDao.SmsTemplateName(smsTemplateId);
    }
    
    

    @Override
    public String sendSms(SmsSendData smsData, int customerId) {
        // common method for sending SMS 
        InputStream in = null;
        String result = null;
        URL url = null;
        boolean smsStatus = false;
        StringBuilder totalResult = new StringBuilder();
        try {
            // Build the message that we want to send
            String urlString = "http://www.smsgatewaycenter.com/library/send_sms_2.php?UserName=healthspring&Password=873457256&Type=Bulk&To=" + smsData.getSmsPhoneNos() + "&Mask=HSPRNG&Message=";
            url = new URL(urlString + smsData.getEncodedSmsBody());
            System.out.println(urlString + smsData.getSmsBody());
            in = url.openStream();
            //System.out.println("Input string=" + in.available());
            BufferedReader bin = new BufferedReader(new InputStreamReader(in));
            while ((result = bin.readLine()) != null) {
                //System.out.println(result);
                totalResult.append(result);
                if (result.contains("SUCCESS")) {
                    //  do success
                  //  System.out.println("Success found in the response string");
                    smsStatus = true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (smsStatus) {

            this.smsDao.addSms(customerId, smsData.getSmsTemplateId(), smsData.getSmsBody(), smsData.getSmsPhoneNos(), 1, totalResult.toString());

            return totalResult.toString();
        } else {

            this.smsDao.addSms(customerId, smsData.getSmsTemplateId(), smsData.getSmsBody(), smsData.getSmsPhoneNos(), 2, "Temporary failure: " + totalResult.toString());

            return "Temporary failure: " + totalResult.toString();
        }

    }

    @Override
    public void reSendSms(SmsDetails smsDetails, int customerId) {
        System.out.println("inside reSendSms");
        InputStream in = null;
        String result = null;
        URL url = null;
        boolean smsStatus = false;
        StringBuilder totalResult = new StringBuilder();
        try {
            smsDetails.setAttempts(smsDetails.getAttempts() + 1);
            String smsBody = java.net.URLEncoder.encode(smsDetails.getMessage().trim(), "UTF-8");
            System.out.println("smsBody:"+smsBody);
            String urlString = "http://www.smsgatewaycenter.com/library/send_sms_2.php?UserName=healthspring&Password=873457256&Type=Bulk&To=" + smsDetails.getPhoneNo() + "&Mask=HSPRNG&Message=";
            url = new URL(urlString + smsBody);
  //          System.out.println("url:"+url);
            in = url.openStream();
    //        System.out.println("in :"+in);
            BufferedReader bin = new BufferedReader(new InputStreamReader(in));
            while ((result = bin.readLine()) != null) {

                totalResult.append(result);
                if (result.contains("SUCCESS")) {
                    //  do success
      //              System.out.println("Success found in the response string");
                    smsStatus = true;
                }
            }
        } catch (Exception e) {
        }
        if (smsStatus) {
        //    System.out.println("smsStatus :"+smsStatus);
            int statusId = 1;//1 for sent
            smsDetails.setSmsStatusId(statusId);
            String totalResults=totalResult.toString();
            smsDetails.setResponse(totalResults);
            this.smsDao.UpdateSms(smsDetails);
            //return totalResult.toString();
        } else {
          //  System.out.println("inside else");
            int statusId = 2;//2 for not sent
            smsDetails.setSmsStatusId(statusId);
            String totalResults="Temporary failure: " + totalResult.toString();
            smsDetails.setResponse(totalResults);
            this.smsDao.UpdateSms(smsDetails);
            //return "Temporary failure: " + totalResult.toString();
        }
    }

    @Override
    public List<Map<String, Object>> reportSmsStatus(String startDate, String stopDate) {
        return this.smsDao.reportSmsStatus(startDate, stopDate);
    }

    @Override
    public List<SmsDetails> getFailedSmsListForReport(String startDate, String stopDate) {
        return this.smsDao.getFailedSmsListForReport(startDate,stopDate);
    }

    @Override
    public List<SmsDetails> getFailedSmsListDateWise(String startDate, String stopDate) {
        return this.smsDao.getFailedSmsListDateWise(startDate, stopDate);
    }

    @Override
    public void resendSmsViaButton(int smsId) {
        this.smsDao.resendSmsViaButton(smsId);
    }

    @Override
    public List<SmsDetails> getSuccessSmsListForReport(String startDate, String stopDate) {
        return this.smsDao.getSuccessSmsListForReport(startDate,stopDate);
    }

    @Override
    public List<SmsDetails> getPendingSmsListForReport(String startDate, String stopDate) {
        return this.smsDao.getPendingSmsListForReport(startDate,stopDate);
    }
}
